#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
全量日志诊断脚本：用于彻底排查为何无法匹配 onClick + switch
"""

import sys
import re
from pathlib import Path

def hex_dump(data, length=16):
    """生成可读的十六进制转储"""
    lines = []
    for i in range(0, len(data), length):
        chunk = data[i:i+length]
        hex_part = ' '.join(f'{b:02x}' for b in chunk)
        ascii_part = ''.join(chr(b) if 32 <= b < 127 else '.' for b in chunk)
        lines.append(f"{i:04x}  {hex_part:<{length*3}}  {ascii_part}")
    return '\n'.join(lines)

def safe_repr(s):
    """安全 repr，高亮不可见字符"""
    return repr(s).replace('\\u200b', '\\u200b[ZERO_WIDTH_SPACE]') \
                  .replace('\\u200c', '\\u200c[ZERO_WIDTH_NONJOINER]') \
                  .replace('\\u200d', '\\u200d[ZERO_WIDTH_JOINER]') \
                  .replace('\\ufeff', '\\ufeff[BOM]')

def main():
    if len(sys.argv) != 2:
        print("用法: python full_debug.py <Java文件>")
        sys.exit(1)

    file_path = Path(sys.argv[1])
    if not file_path.is_file():
        print(f"❌ 文件不存在: {file_path}")
        sys.exit(1)

    print("=" * 80)
    print(f"🔍 开始诊断文件: {file_path}")
    print("=" * 80)

    # 1. 读取原始字节
    with open(file_path, 'rb') as f:
        raw_bytes = f.read()

    print("\n📄 原始文件前 128 字节（十六进制）:")
    print(hex_dump(raw_bytes[:128]))

    # 检查 BOM
    if raw_bytes.startswith(b'\xef\xbb\xbf'):
        print("\n⚠️  检测到 UTF-8 BOM (\\xef\\xbb\\xbf)")
    elif raw_bytes.startswith(b'\xff\xfe'):
        print("\n⚠️  检测到 UTF-16 LE BOM")
    elif raw_bytes.startswith(b'\xfe\xff'):
        print("\n⚠️  检测到 UTF-16 BE BOM")

    # 2. 尝试多种编码读取
    encodings = ['utf-8-sig', 'utf-8', 'gbk', 'gb2312', 'utf-16']
    lines = None
    used_encoding = None

    for enc in encodings:
        try:
            text = raw_bytes.decode(enc)
            lines = text.splitlines(keepends=True)
            used_encoding = enc
            print(f"\n✅ 成功使用编码: {enc}")
            break
        except Exception as e:
            print(f"❌ 编码 {enc} 失败: {e}")

    if lines is None:
        print("\n💥 所有编码尝试失败！文件可能损坏或使用罕见编码。")
        return

    print(f"\n📊 文件共 {len(lines)} 行")

    # 3. 逐行分析
    found_onclick_line = None
    found_switch_line = None

    ONCLICK_KEYWORD = 'public void onClick(View'
    SWITCH_KEYWORD = 'switch ('

    print("\n" + "="*80)
    print("🔍 逐行分析（仅显示含 'onClick' 或 'switch' 的行）")
    print("="*80)

    for i, line in enumerate(lines, 1):
        stripped = line.rstrip('\r\n')
        has_onclick = ONCLICK_KEYWORD in line
        has_switch = 'switch (' in line and '.getId()' in line

        if has_onclick or has_switch:
            print(f"\n--- 行 {i} ---")
            print(f"原始字节 (UTF-8): {line.encode('utf-8', errors='replace').hex()}")
            print(f"字符串内容      : {safe_repr(line)}")
            print(f"去除换行后      : {safe_repr(stripped)}")
            print(f"是否含 'onClick': {has_onclick}")
            print(f"是否含 'switch': {has_switch}")

            # 尝试提取参数名
            if has_onclick:
                m = re.search(r'onClick\s*$\s*View\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*$', line)
                if m:
                    param = m.group(1)
                    print(f"✅ 成功提取 onClick 参数名: '{param}'")
                    found_onclick_line = (i, param, stripped)
                else:
                    print("❌ 未能从 onClick 行提取参数名！正则未匹配。")

            if has_switch:
                m = re.search(r'switch\s*$\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\.getId\($\s*\)', line)
                if m:
                    var = m.group(1)
                    print(f"✅ 成功提取 switch 变量名: '{var}'")
                    found_switch_line = (i, var, stripped)
                else:
                    print("❌ 未能从 switch 行提取变量名！正则未匹配。")

    # 4. 判断是否可匹配
    print("\n" + "="*80)
    print("🎯 匹配结论")
    print("="*80)

    if found_onclick_line and found_switch_line:
        onclick_line, onclick_param, _ = found_onclick_line
        switch_line, switch_var, _ = found_switch_line
        if switch_line > onclick_line and switch_line <= onclick_line + 10:
            if onclick_param == switch_var:
                print(f"✅ 理论上应匹配成功！")
                print(f"   onClick 在行 {onclick_line}，参数: {onclick_param}")
                print(f"   switch 在行 {switch_line}，变量: {switch_var}")
                print("   👉 脚本应该转换此文件！")
            else:
                print(f"⚠️  参数名不一致: onClick={onclick_param}, switch={switch_var}")
        else:
            print(f"⚠️  switch 距离 onClick 太远（>10 行）")
    else:
        if not found_onclick_line:
            print("❌ 未检测到任何包含 'public void onClick(View' 的行")
        if not found_switch_line:
            print("❌ 未检测到任何包含 'switch (... .getId())' 的行")

    print("\n💡 建议：")
    print("  - 如果这里显示应匹配但脚本没转，请检查脚本是否用了旧版正则")
    print("  - 如果参数名提取失败，请检查行中是否有注释、换行或不可见字符")
    print("  - 可尝试用 VS Code / Notepad++ 查看不可见字符（开启“显示所有字符”）")

if __name__ == '__main__':
    main()